﻿using SaaS.Cache.Auths;
using SaaS.Cache.Sites;
using SaaS.Model.Entity.Sites;
using SaaS.Model.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XCore.Dependency;
using XCore.Extensions;

namespace Web.Admin.Services.Sites
{
    public class RoleAppService : AdminApplictionServiceBase, ISingletonDependency
    {
        private readonly AdminAuthCacheService _adminAuthCacheService;
        public RoleAppService(AdminAuthCacheService adminAuthCacheService)
        {
            _adminAuthCacheService = adminAuthCacheService;
        }
        /// <summary>
        /// 创建与编辑
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="description"></param>
        /// <param name="permissions"></param>
        /// <returns></returns>
        public bool CreateOrEdit(int id, string name, string description, string[] permissions)
        {
            if (name.IsNullOrWhiteSpace()) throw new AdminException("角色名不能为空", AdminLoggerSource.Role);
            SiteRole role = new SiteRole
            {
                Id = id,
                Name = name,
                Description = description,
                Permissions = string.Join(",", permissions),
                SiteId = Session.SiteId
            };
            if (role.Id == 0)
            {
                role.Id = Repository.InsertAndGetId(role);
                Logger.Log("新增角色", AdminLoggerSource.Role);
            }
            else
            {
                Repository.Update(role, c => c.Id == id, c => c.Name, c => c.Description, c => c.Permissions);
                Logger.Log("修改角色信息", AdminLoggerSource.Role);
            }
            _adminAuthCacheService.SavePermission(role.Id, permissions);
            return true;
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            if (ADC.SiteAdmins.Any(c => c.RoleId == id)) throw new AdminException("角色包含用户，不可删除", AdminLoggerSource.Role);
            return Repository.Delete<SiteRole>(id) && Logger.Log("删除角色", AdminLoggerSource.Role);
        }
        /// <summary>
        /// 更新角色人数
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="oldId"></param>
        /// <returns></returns>
        public bool RefreshCount(int roleId, int? oldId = null)
        {
            int count = 0;
            if (oldId.HasValue)//修改管理员角色，更新旧角色人数
            {
                count = ADC.SiteAdmins.Count(c => c.RoleId == oldId.Value);
                Repository.Update<SiteRole, int>(oldId.Value, c => c.Count, count);
            }

            count = ADC.SiteAdmins.Count(c => c.RoleId == roleId);//修改新角色人数
            return Repository.Update<SiteRole, int>(roleId, c => c.Count, count);
        }
    }
}
